package com.oscar.ehome.view.setview;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.setbean.opinion.CustomConstants;
import com.oscar.ehome.bean.setbean.opinion.ImageItem;
import com.oscar.ehome.bean.setbean.opinion.IntentConstants;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.view.setview.adapter.ImageGridAdapter;

import net.tycmc.bulb.androidstandard.utils.JsonUtils;

import org.apache.commons.collections.MapUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 图片选择
 */
public class ImageChooseActivity extends BasesActivity {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    /**
     * 存储手机中所有图片的list集合
     */
    private List<Map<String, Object>> paths = new ArrayList<Map<String, Object>>();
    private List<String> listpath = new ArrayList<>();


    private String mBucketName;
    private int availableSize;
    private GridView mGridView;
    private TextView cancelTv;
    private ImageGridAdapter mAdapter;
    private Button mFinishBtn;
    private HashMap<String, ImageItem> selectedImgs = new HashMap<String, ImageItem>();

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.act_image_choose);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(ImageChooseActivity.this).getSystemConfig().getColor()));
        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);

        getAllImagePath();
        if (TextUtils.isEmpty(mBucketName)) {
            mBucketName = "请选择";
        }
        availableSize = getIntent().getIntExtra("availableSize", 0);
        initView();
        initListener();

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    private void initView() {
        titleTopbar.setText(mBucketName);

        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mAdapter = new ImageGridAdapter(ImageChooseActivity.this, paths);
        mGridView.setAdapter(mAdapter);
        mFinishBtn = (Button) findViewById(R.id.finish_btn);
    }

    private void initListener() {
        mFinishBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent intent = new Intent();
                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("list", listpath);
                Log.e("huilaila", "onActivityResult: "+maps.size());
                intent.putExtra("result_photo", JsonUtils.toJson(maps));
                setResult(3, intent);
                finish();

            }

        });

        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                boolean selects = MapUtils.getBoolean(paths.get(position), "isSelect");
                if (!selects) {//是未选中
                    if (listpath.size() >= availableSize) {
                        Toast.makeText(ImageChooseActivity.this,
                                "最多选择" + availableSize + "张图片",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    paths.get(position).put("isSelect", true);
                    listpath.add(MapUtils.getString(paths.get(position), "imagePath"));
                } else {
                    paths.get(position).put("isSelect", false);
                    listpath.remove(MapUtils.getString(paths.get(position), "imagePath"));
                }

                mAdapter.setLists(paths);
                mFinishBtn.setText("完成" + "(" + listpath.size() + "/"
                        + availableSize + ")");
            }

        });
        titleLayoutLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 获得所有图片的路径
     */
    private void getAllImagePath() {
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        //遍历相册
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<String, Object>();
            Log.e("lujingchakan", "getAllImagePath: "+ cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
            //将图片路径添加到集合
            if(path.contains("Camera/")){
                map.put("imagePath", path);
                map.put("isSelect", false);
                paths.add(map);
            }

        }
        cursor.close();
    }

}